﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

using System.Web.Script.Serialization;

namespace ClassCommon
{
    /**
        请求地址：http://v.juhe.cn/sms/send
        请求参数：mobile=18571656584&tpl_id=70136&tpl_value=%2523code%2523%253d431515&dtype=&key=5e0efcba1666d864fb179fe4b94a1db7
        请求方式：GET
     * 
     * 
     * {
	"reason":"操作成功",
	"result":{
		"sid":"201804041551439012636",
		"fee":1,
		"count":1
	},
	"error_code":0
}
     */

    /// <summary>
    /// 手机验证码
    /// </summary>
    public class PhoneValidateCodeHelper
    {
        /* 后台配置的key */
        private const string key = "5e0efcba1666d864fb179fe4b94a1db7";
        /// <summary>
        /// 短息模板编号，去聚合数据后台自己看
        /// https://www.juhe.cn/sms
        /// </summary>
        private const int tmp_id = 70136;

        private const string Sms_Get_URL = "http://v.juhe.cn/sms/send?";
        /**
         tpl_value : #code#=431515 需要对这个部分进行urlencode
         */
        private const string Sms_Get_Params = "mobile={0}&tpl_id={1}&tpl_value={2}&dtype=json&key={3}";

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="phoneNum">手机号码</param>
        /// <returns>返回随机验证码</returns>
        public static bool SendValidatePhoneCode(string phoneNum)
        {
            // 1. 生成随机4位验证码
            string randCode = new Random().Next(1111, 9999).ToString();

            // Console.WriteLine("code is : {0}",randCode);
            // 2. 对验证码参数进行 urlencode 操作。
            string encodeCode = HttpUtility.UrlEncode(string.Format("#code#={0}", randCode));
            // 3. 创建url请求链接字符串
            string requestURL = Sms_Get_URL + string.Format(Sms_Get_Params, phoneNum, tmp_id, encodeCode, key);


            // 统一资源定位符
            Uri uri = new Uri(requestURL);
            // 创建请求对象
            HttpWebRequest request = WebRequest.Create(requestURL) as HttpWebRequest;
            request.Method = "GET";
            // request.ContentType = ""

            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            // 获得响应流
            Stream reponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(reponseStream, Encoding.GetEncoding("utf-8"));
            string retString = myStreamReader.ReadToEnd();


            // 关闭响应流
            response.Close();
            reponseStream.Close();
            // 关闭本地IO流
            myStreamReader.Close();
            reponseStream.Dispose();
            myStreamReader.Dispose();

            JavaScriptSerializer jsSerializer = new JavaScriptSerializer();

            ResponseData responseJsonObj = jsSerializer.Deserialize<ResponseData>(retString);
            // Console.WriteLine(responseJsonObj.ToString());
            if (responseJsonObj.error_code == 0)
            { 
                // 记录手机验证码，并发送到浏览器cookie以备验证。
                string codeEncry = EncryptHelper.Encrypt(randCode);
                // ....
                HttpCookieHelper.SetCookie(ConfigSetting.Cookie_PhoneValidateCode, codeEncry);

                return true;
            }

            return false;
        }

    }


    [Serializable]
    public class ResponseData
    {
        public string reason { get; set; }
        public Result result { get; set; }
        public int error_code { get; set; }


        public override string ToString()
        {
            // return base.ToString();

            return string.Format("reason : {0} result.sid : {1} result.fee : {2} result.count : {3} error_code : {4}",
                    this.reason,
                    this.result.sid,
                    this.result.fee,
                    this.result.count,
                    this.error_code
                );
        }
    }

    [Serializable]
    public class Result
    {
        public string sid { get; set; }
        public int fee { get; set; }
        public int count { get; set; }
    }
}
